package com.example.waimai.handler;

import com.example.waimai.context.ResultMsg;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

@ControllerAdvice(basePackages = "com.example.waimai.controller")
public class ResponseControllerAdvice implements ResponseBodyAdvice<Object> {
    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        // 当返回类型为 resultmsg 类型时就不用拦截处理了
        return ! returnType.getParameterType().equals(ResultMsg.class);
    }

    @Override
    public Object beforeBodyWrite(Object data, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {

        String genericName = returnType.getGenericParameterType().getTypeName();
        ServletServerHttpResponse rResponse = (ServletServerHttpResponse) response;
        if(rResponse != null){
            rResponse.getServletResponse().setHeader("Generic-Class",genericName);
        }
        // 额外处理String
        if (returnType.getGenericParameterType().equals(String.class)) {
            ObjectMapper objectMapper = new ObjectMapper();
            try {
                // 将数据包装在ResultVO里后，再转换为json字符串响应给前端
                return objectMapper.writeValueAsString(new ResultMsg<>(data));
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }
        }

        return new ResultMsg<>(data);
    }
}
